// pages/taskDetail/taskDetail.js
var app = getApp()
const QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
const wxMap = new QQMapWX({
  key: 'AB3BZ-QEI6J-7SAFK-FV2J4-YEAR7-C7FYZ' // 必填
});
Page({

  /**
   * 页面的初始数据
   */
  data: {
    baseUrl: '',
    isHidden: true,
    baomingText: '我要报名',
    taskid: '',
    task: {},
    position:'',
    isclick:true
  }, 
  gotoindex: function () {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  gotobaoming:function(){
    var user = wx.getStorageSync('user');
    if (user.phone == '' || user.phone == null || user.phone == "null") {
      wx.showToast({
        title: "请完善信息",
        duration: 1500
      })
      setTimeout(function () {
        wx.navigateTo({
          url: '/pages/personaldetail/personaldetail',
        })
      }, 1500)
      return false;
    }
    if (user.school == '' || user.school == null || user.school == "null") {
      wx.showToast({
        title: "请完善信息",
        duration: 1500
      })
      setTimeout(function () {
        wx.navigateTo({
          url: '/pages/personaldetail/personaldetail',
        })
      }, 1500)
      return false;
    }
    if (this.data.isHidden) {
      if (this.data.isclick) {
        this.setData({
          isclick: false
        })
        setTimeout(() => {
          this.setData({
            isclick: true
          })
        }, 5000);
      }
      this.gotoBaoming(this.data.taskid)
    } else {
      // this.deltoBaoming(this.data.taskid)
    }
  }, 
  //取消报名
  deltoBaoming: function (id) {
    var accesstoken = wx.getStorageSync('accesstoken')
    wx.request({
      url: 'https://api.tianlala.com.cn/job-records', // 仅为示例
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': accesstoken
      },
      method: 'DELETE',
      data: {
        job_id: id
      },
      success: (res) => {
        console.log(res, '取消成功')
        if (res.statusCode == 200) {
          this.setData({
            isHidden: true,
            baomingText: '我要报名'
          })
          wx.showToast({
            title: res.data.msg,
          })
        }

      },
      fail: (res) => {
        console.log(res, '失败')
      }
    })
  },
  //报名
  gotoBaoming: function (id) {
    var accesstoken = wx.getStorageSync('accesstoken')
    wx.request({
      url: 'https://api.tianlala.com.cn/job-records', // 仅为示例，并非真实的接口地址
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': accesstoken
      },
      method: 'POST',
      data: {
        jid: id
      },
      success: (res) => {
        console.log(res, '报名成功')
        if (res.statusCode == 200) {

          // this.setData({
          //   isHidden: false,
          //   baomingText: '取消报名'
          // })
          // wx.showToast({
          //   title: '报名成功',
          // })

          wx.request({
            url: 'https://api.tianlala.com.cn/order',
            data: {
              out_trade_no: res.data.order_id
            },
            method: 'POST',
            header: {
              // 'content-type': 'application/json', // 默认值
              'Authorization': accesstoken
            },
            success:(res) => {
              console.log(res, "支付")
              wx.requestPayment({
                timeStamp: res.data.result.timeStamp,
                nonceStr: res.data.result.nonceStr,
                package: res.data.result.package,
                signType: res.data.result.signType,
                paySign: res.data.result.paySign,
                success:(res)=> {
                  console.log(res, "支付成功");
                  this.setData({
                    isHidden: false,
                    // baomingText: '取消报名'
                    baomingText: '已报名'
                  })
                  wx.showToast({
                    title: '提交成功',
                  })
                  
                  setTimeout(() => {
                    wx.switchTab({
                      url: '/pages/task/task',
                    })
                  }, 2000)
                },
                fail(res) {
                  console.log(res, "支付失败");
                }
              })
            }
          });

        }

      },
      fail: (res) => {
        console.log(res, '失败')
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      taskid: options.taskid,
      baseUrl: app.baseUrl,
    })
    wx.hideShareMenu();
    this.getTask(options.taskid)
  },

  getTask:function(taskid){
    var accesstoken = wx.getStorageSync('accesstoken')
    wx.request({
      url: 'https://api.tianlala.com.cn/missions/' + taskid, // 仅为示例，并非真实的接口地址
      header: {
        'content-type': 'application/json', // 默认值
        'Authorization': accesstoken
      },
      method: 'GET',
      data: {
      },
      success: (res) => {
        console.log(res, '单个任务 成功')
        wxMap.reverseGeocoder({
          location: {
            latitude: res.data.latitude,
            longitude: res.data.longitude,
          },
          success: (res) => {
            console.log(res.result.formatted_addresses.recommend, '地址名称');
            this.setData({
              position: res.result.formatted_addresses.recommend
            })
          },
        });
        this.setData({
          task: res.data
        })
        if (res.data.is_sign_up) {
          this.setData({
            isHidden: false,
            // baomingText: '取消报名'
            baomingText: '已报名'
          })
        }
        this.setData({
          longitude: res.data.longitude,
          latitude: res.data.latitude,
          markers: [{
            iconPath: '/img/fabu/position.png',
            id: 0,
            longitude: res.data.longitude,
            latitude: res.data.latitude,
            width: 30,
            height: 30
          }],
          controls: [{
            id: 1,
            iconPath: '/img/fabu/position.png',
            position: {
              left: 0,
              top: 0,
              width: 30,
              height: 30
            },
            clickable: true
          }]
        })

      },
      fail: (res) => {
        console.log(res, '失败')
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  reportUrl() {
    wx.navigateTo({
      url: '/pages/report/report',
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.checkLogin(this.data.taskid)
  },
  checkLogin: function (taskid){
    wx.checkSession({
      success: () => {
        //session_key 未过期，并且在本生命周期一直有效
        console.log('未过期')
        //判断用户是否授权
        wx.getSetting({
          success: (data) => {
            // console.log(data);
            if (data.authSetting['scope.userInfo']) {
              //用户已经授权
              //获取用户登录信息
              var value = wx.getStorageSync('userInfo')
              //是否有信息
              if (!value.nickName) {
                //没有用户信息
                wx.showToast({
                  title: '请登录',
                  icon: 'none',
                  duration: 1000
                })
                //重新登录
                wx.clearStorageSync();
                wx.navigateTo({
                  url: '/pages/login/login?id=' + taskid + '&flag=2',
                })
              } else {

              }
            } else {
              //用户未授权
              //重新登录
              wx.clearStorageSync();
              wx.navigateTo({
                url: '/pages/login/login?id=' + taskid + '&flag=2',
              })
            }
          }
        });
      },
      fail() {
        // session_key 已经失效，需要重新执行登录流程
        //重新登录
        wx.clearStorageSync();
        wx.navigateTo({
          url: '/pages/login/login?id=' + taskid + '&flag=2',
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    console.log(e.target.dataset.id)
    return {
      title:'任务：' + e.target.dataset.title,
      path: '/pages/taskDetail/taskDetail?taskid=' + e.target.dataset.id
    }
      // imageUrl: app.baseUrl + 'login/logo.png'
  }
})